<script setup lang="tsx">
import { ElInput } from 'element-plus'
import {
  defaultContextMenuData,
  useHandleElectricity,
} from '../hooks/handle-electricity'
import type { PublicProps } from './type'
import type {
  EnterpriseMonthReportSaveOrUpdateElectric,
  EnterpriseMonthReportSaveOrUpdateElectricParams,
  TableColumn,
} from '@/types'
import {
  queryListElectric,
  saveOrUpdateElectric,
} from '@/api/modules/enterpriseMonthReport'
import type { ContextMenuData } from '@/components/type'

// ------------------use------------------
// #region

const props = withDefaults(defineProps<PublicProps>(), {
  preview: false,
})
const { $message } = useCurrentInstance()
const { userInfo } = storeToRefs(useUserStore())
const { loading, withLoading } = useDefineLoading()
const [tableData, setTableData]
  = useState<EnterpriseMonthReportSaveOrUpdateElectricParams>(
    [],
  )
const [position, setPosition] = useState({
  x: 0,
  y: 0,
})
const [isContextMenu, setIsContextMenu] = useState(false)
const [contextMenuData, setContextMenuData] = useState({
  ...defaultContextMenuData,
})
const {
  data,
  info,
  spanMethod,
  updateCount,
  isOnly,
  updateGroupAssociationValue,
  removeRow,
  appendRow,
  getMarkErrorState,
  markErrorState,
} = useHandleElectricity(tableData, props.dataTime)
const [targetRow, setTargetRow]
  = useState<EnterpriseMonthReportSaveOrUpdateElectric>(
    {} as any,
  )
const { errorCell, removeError, clearError }
  = useTableErrorCell(() => viewTableRef.value)
// #endregion
// ------------------静态变量------------------
// #region
const columns: TableColumn<EnterpriseMonthReportSaveOrUpdateElectric>[]
  = [
    {
      key: uuid(),
      width: '80',
      prop: 'line',
      label: '线路',
      render({ row, index }) {
        const m = row.line.split('-')
        const ci = columnsProps.findIndex(
          str => str === 'line',
        )
        return m.length > 1
          ? ''
          : h(ElInput, {
            disabled: props.preview,
            modelValue: row.line,
            onInput: (value: number | string) => {
              const b = isOnly('line', String(value))

              if (!b) {
                errorCell(
                  index + 1,
                  ci + 1,
                  '线路不能重复！',
                )
                markErrorState(row)
              }
              else {
                removeError(index + 1, ci + 1)
                markErrorState(row, true)
              }

              row.line = String(value)
            },
            onBlur: () => {
              !getMarkErrorState(row)
              && updateCount(row.line, String(row.line))
            },
          })
      },
    },
    {
      key: uuid(),
      width: '80',
      prop: 'index',
      label: '序号',
      render({ row }) {
        return row.line.split('-').at(-1)!
      },
    },
    {
      key: uuid(),
      label: '用电单位',
      prop: 'useUnit',
      render({ row, index }) {
        return h(ElInput, {
          disabled: props.preview,
          modelValue: row.useUnit,
          onInput: (value: number | string) => {
            row.useUnit = String(value)
          },
          onBlur: () => {
            const b = Verify.isEmpty(row.useUnit)
            const ci = columnsProps.findIndex(
              str => str === 'useUnit',
            )
            if (b) {
              errorCell(
                index + 1,
                ci + 1 - 1,
                '不能为空！',
              )
            }
            else {
              removeError(index + 1, ci + 1 - 1)
            }
          },
        })
      },
    },
    {
      key: uuid(),
      label: '上月止码',
      prop: 'lastMonthValue',
    },
    {
      key: uuid(),
      label: '本月止码',
      prop: 'thisMonthValue',
      render({ row }) {
        return h(ElInput, {
          disabled: props.preview,
          modelValue: row.thisMonthValue,
          onInput: (value: number | string) => {
            row.thisMonthValue = value as number
          },
          onBlur: () => {
            row.thisMonthValue = Number(row.thisMonthValue)
          },
        })
      },
    },
    {
      key: uuid(),
      label: '倍率',
      prop: 'magnification',
      render({ row }) {
        return h(ElInput, {
          disabled: props.preview,
          modelValue: row.magnification,
          onInput: (value: number | string) => {
            row.magnification = value as number
          },
          onBlur: () => {
            row.magnification = Number(row.magnification)
          },
        })
      },
    },
    {
      key: uuid(),
      label: '有功电量(kw.h)',
      prop: 'usefulElectric',
      render({ row }) {
        return h(ElInput, {
          disabled: props.preview,
          modelValue: row.usefulElectric,
          onInput: (value: number | string) => {
            row.usefulElectric = value as number
          },
          onBlur: () => {
            row.usefulElectric = Number(row.usefulElectric)
          },
        })
      },
    },
    {
      key: uuid(),
      label: '线变损',
      prop: 'lineLoss',
      render({ row }) {
        return h(ElInput, {
          disabled: props.preview,
          modelValue: row.lineLoss,
          onInput: (value: number | string) => {
            console.log(value)

            row.lineLoss = value as number
          },
          onBlur: () => {
            row.lineLoss = Number(row.lineLoss)
          },
        })
      },
    },
    {
      key: uuid(),
      label: '总电量',
      prop: 'countValue',
      render({ row }) {
        row.countValue = +(
          row.lineLoss * row.usefulElectric
        ).toFixed(2)
        return row.countValue
      },
    },
    {
      key: uuid(),
      label: '核减小计',
      prop: 'offset',
      render({ row }) {
        return h(ElInput, {
          disabled: props.preview,
          modelValue: row.offset,
          onInput: (value: number | string) => {
            const [key] = row.line!.split('-')
            updateGroupAssociationValue(
              key!,
              'offset',
              value as number,
            )
          },
          onBlur: () => {
            const [key] = row.line!.split('-')
            updateGroupAssociationValue(
              key!,
              'offset',
              Number(row.offset),
            )
          },
        })
      },
    },
    {
      key: uuid(),
      label: '实际有功电量(kw.h)',
      prop: 'realUsefulElectric',
      render({ row }) {
        const m = row.line!.split('-')

        row.realUsefulElectric = m.at(1)
          ? 0
          : +(row.countValue - row.offset).toFixed(2)
        return row.realUsefulElectric
      },
    },
    {
      key: uuid(),
      label: '单价(元)',
      prop: 'unitPrice',
      render({ row }) {
        return h(ElInput, {
          disabled: props.preview,
          modelValue: row.unitPrice,
          onInput: (value: number | string) => {
            row.unitPrice = value as number
          },
          onBlur: () => {
            row.unitPrice = Number(row.unitPrice)
          },
        })
      },
    },
    {
      key: uuid(),
      label: '电费(元)',
      prop: 'countPrice',
      render({ row }) {
        row.countPrice = +(
          row.unitPrice * row.realUsefulElectric
        ).toFixed(2)
        return row.countPrice
      },
    },
  ]
const columnsProps = columns.map(item => item.prop)
// #endregion
// ------------------动态变量------------------
// #region

// #endregion
// ------------------ref-----------
// #region
const viewTableRef = ref()
// #endregion
// ------------------reactive------
// #region

// #endregion
// ------------------computed------
// #region

// #endregion
// ------------------生命周期------------------
// #region
onMounted(() => {
  clearError()
  getTableData()
})
// #endregion
// ------------------内置方法---------------------
// #region

// #endregion
// ------------------方法---------------------
// #region
async function getTableData() {
  const { data: res } = await withLoading(
    queryListElectric,
  )({
    tenantId: userInfo.value.tenantId ?? 5,
    dataTime: props.dataTime,
  })
  const m = [...res]
  if (props.preview) {
    console.log(123)

    m.forEach((item: any) => Object.freeze(item))
  }
  setTableData(m)
  console.log(props.preview)
}
function handleTableRowContextmenu(row: any, __: any, e: PointerEvent) {
  setPosition({
    x: e.clientX,
    y: e.clientY,
  })
  setIsContextMenu(true)
  setTargetRow(row)
  const m = row.line!.split('-')
  if (m[1]) {
    setContextMenuData([
      ...defaultContextMenuData.slice(0, 1),
      {
        key: 3,
        label: '下方添加行',
      },
    ])
  }
  else {
    setContextMenuData([...defaultContextMenuData])
  }
}
function handleMenuClick(row: Partial<ContextMenuData>) {
  switch (row.key) {
    case 1:
      removeRow(targetRow.value)
      return
    case 2:
      appendRow(targetRow.value)
      return
    case 3:
      appendRow(targetRow.value, true)
  }
}
async function saveStage() {
  const isValid = viewTableRef.value.validate()
  if (!isValid) {
    $message.warning('请将表格中错误项修改后再提交！')
    return
  }
  const m = [
    ...data.value.filter(item => Boolean(item.line)),
    info.value,
  ]
  console.log(m)

  const { code } = await withLoading(saveOrUpdateElectric)(
    m,
  )
  if (code !== 200)
    return
  $message.success('报表保存成功')
  getTableData()
}
// #endregion
</script>

<template>
  <div
    class="height-fill flex-direction electricity-report flex gap-sm"
  >
    <drag-modal title="填报信息">
      <ElForm
        :model="info"
        class="form"
        size="small"
        :disabled="preview"
        label-position="top"
      >
        <ElFormItem label="部门主管签字">
          <ElInput
            v-model="info.director"
            type="text"
            class="report-input free"
          />
        </ElFormItem>
        <ElFormItem label="监表人">
          <ElInput
            v-model="info.watchman"
            type="text"
            class="report-input free"
          />
        </ElFormItem>
        <ElFormItem label="抄表人">
          <ElInput
            v-model="info.meterReader"
            type="text"
            class="report-input free"
          />
        </ElFormItem>
        <ElFormItem label="制表人">
          <ElInput
            v-model="info.tabulator"
            type="text"
            class="report-input free"
          />
        </ElFormItem>
      </ElForm>
    </drag-modal>
    <slot
      name="title"
      :time="dataTime"
      :save-stage="saveStage"
      :download="() => viewTableRef.export()"
    />
    <b-scrollbar class="flex-fillRemaining">
      <view-table
        ref="viewTableRef"

        show-summary excel border
        :preview="preview"
        :show-overflow-tooltip="false"
        :loading="loading"
        :columns="columns"
        :data="data as any"
        :show-toolbox="false"
        :span-method="spanMethod"
        @row-contextmenu="handleTableRowContextmenu"
      />
      <div class="margin-top-xs view-table-description">
        <p class="title">
          说明：
        </p>
        <p>1．总电量=线变损 × 有功电量(kw.h)。</p>
        <p>2．实际有功电量(kw.h)=总电量 × 核减小计。</p>
        <p>3．电费(元)=单价(元) × 实际有功电量(kw.h)。</p>
      </div>
    </b-scrollbar>

    <context-menu
      v-model="isContextMenu"
      :data="contextMenuData"
      :position="position"
      @menu-click="handleMenuClick"
    />
  </div>
</template>

<style>
.backslash-cell {
  position: relative;
  background-color: red;
  &::before {
    content: '';
    position: absolute;
  }
}
</style>

<style lang="scss" scoped>
//------------------组件样式------------------
//-------------样式穿透-------------
</style>
